package cn.sc.allinpay.allfavour.business.distdetail;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.pai.common.listener.OnPromptListener;
import cn.pai.common.utils.AmtUtils;
import cn.pai.mvp.callback.MpCallBack;
import cn.pai.mvp.intervenor.Intervenor;
import cn.pai.mvp.presenter.PaiPresenter;
import cn.sc.allinpay.allfavour.app.Constant;
import cn.sc.allinpay.allfavour.base.db.DbDao;
import cn.sc.allinpay.allfavour.business.common.data.CashierData;
import cn.sc.allinpay.allfavour.business.common.data.ConfigData;
import cn.sc.allinpay.allfavour.business.common.data.DistCouponData;
import cn.sc.allinpay.allfavour.business.common.data.DistCouponRecord;
import cn.sc.allinpay.allfavour.module.device.DeviceLogin;
import cn.sc.allinpay.allfavour.module.printer.IPrinter;
import cn.sc.allinpay.allfavour.module.printer.PrintData;
import cn.sc.allinpay.allfavour.module.printer.PrintManager;

/**
 * 发券详情 presenter
 * author：pany
 * on 2017/12/1 11:27
 */
public class DistDetailPresenter extends PaiPresenter<DistDetailContract.View> implements DistDetailContract.Presenter {

    private DistDetailModel model = new DistDetailModel();
    private DistCouponData distData;//发券数据
    private int distNum = 0;//发券数量
    private DistCouponRecord record;//发券记录
    private IPrinter printer;


    @Override
    protected Intervenor createIntervenor() {
        return new Intervenor() {
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                Bundle bundle = view.getBundle();
                distData = bundle.getParcelable(Constant.BundleKey.DISTCOUPON);
            }

            @Override
            public void onResume() {
                super.onResume();
                DeviceLogin.login(view.getContext());
            }

            @Override
            public void onPause() {
                super.onPause();
                DeviceLogin.logout();
            }
        };
    }

    @Override
    public void start() {
        view.showName(distData.getName());
        //0金额 1抵扣 2计次
        if (0 == distData.getAmtType()) {
            view.showType("类型：金额券");
            view.showInventory("库存：" + distData.getTotCoup());
            view.showPriceAmt("面额：" + AmtUtils.changeF2Y(distData.getAmt()));
            view.showNumTitle("发券数量：");
        } else {
            if (1 == distData.getAmtType()) {
                view.showType("类型：抵扣券");
                view.showNumTitle("发券数量：");
            } else {
                view.showType("类型：计次券");
                view.showNumTitle("发券次数：");
            }
            view.showInventory("库存：" + distData.getTotCoup() + distData.getUnit());
            view.showPriceAmt(null);
        }
        view.showExplain(distData.getDesc());
        view.showNumber(String.valueOf(distNum));
        additNumber();
    }

    @Override
    public void reduceNumber() {
        if (distNum > 0) {
            distNum -= 1;
            distData.setUseNum(distNum);
            view.showNumber(String.valueOf(distNum));
        }
    }

    @Override
    public void additNumber() {
        if (distNum < Integer.valueOf(distData.getTotCoup())) {
            distNum += 1;
            distData.setUseNum(distNum);
            view.showNumber(String.valueOf(distNum));
        }
    }

    @Override
    public void reqDistCoupon() {
        if (distNum == 0) {
            view.prompt("发券数量不能为空");
            return;
        }
        view.loading("发券中...");
        List<DistCouponData> distList = new ArrayList<>();
        distList.add(distData);
        model.reqDistCoupon(distList, new MpCallBack<JSONObject, String>() {
            @Override
            public void onSuccess(JSONObject resp) {
                view.loaded();
                JSONObject data = resp.getJSONObject("data");
                String seqNum = data.getString("seqNum");
                String trsTime = data.getString("retTime");
                String url = data.getString("url");
                saveRecord(seqNum, trsTime, url);
                print();
            }

            @Override
            public void onFailure(String response, String message) {
                view.loaded();
                view.prompt(false, message + ",是否继续发券？", new OnPromptListener("确定", "取消") {
                    @Override
                    public void onPositive(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        reqDistCoupon();
                    }

                    @Override
                    public void onNegative(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        view.finish();
                    }
                });
            }
        });
    }

    /**
     * 保存发券流水
     */
    private void saveRecord(String seqNum, String trsTime, String url) {
        DbDao<DistCouponRecord> dbDao = model.getDao(DistCouponRecord.class);
        CashierData cashierData = model.getGlobal().getCashierData();
        ConfigData configData = model.getGlobal().getConfigData();
        record = new DistCouponRecord();
        record.setMerName(configData.getMerName());
        record.setTerId(configData.getTerId());
        record.setTransNo(seqNum + distData.getId());//流水号
        record.setSeqNum(seqNum);//订单号,营销前置订单
        record.setTime(trsTime);
        record.setTransDate(trsTime.substring(0, 8));
        record.setTransTime(trsTime.substring(8));
        record.setOperator(cashierData.getCashierNo());//操作员号码
        record.setOperatorName(cashierData.getCashierName());//操作员名称
        record.setCouponId(distData.getId());//发券ID
        record.setCouponName(distData.getName());//发券名称
        record.setCouponNum(distNum);//售券数量
        record.setCouponType(distData.getAmtType());//发券类型
        record.setCouponAmt(distData.getAmt());//发券面额
        record.setCouponUnit(distData.getUnit());//发券单位
        record.setCouponTotCoup(distData.getTotCoup());//发券库存
        record.setCouponDesc(distData.getDesc());
        record.setUrl(url);
        record.setDistCouponData(JSON.toJSONString(distData));//就是DistCouponData对象的json
        dbDao.add(record);
    }

    public void print() {
        view.loading("发券成功，正在打印...");
        PrintData data = new PrintData();
        data.setMerchantName(model.getGlobal().getConfigData().getMerName());
        data.setTerminalId(model.getGlobal().getConfigData().getTerId());
        data.setOperNo(record.getOperator());
        data.setOperName(record.getOperatorName());
        data.setTime(record.getTime());
        data.setTransName("发券");
        data.setCouponSeqNum(record.getSeqNum());
        data.setCouponName(record.getCouponName());
        data.setCouponType(record.getCouponType());
        data.setCouponUseNum(record.getCouponNum());
        data.setCouponUrl(record.getUrl());
        printer = PrintManager.createPrinter(PrintManager.PRINT_DIST, data);
        printer.print(new IPrinter.OnPrintListener() {
            @Override
            public void onStart(int step) {

            }

            @Override
            public void onSuccess(int step) {
                view.loaded();
                view.prompt(false, "打印成功", new OnPromptListener("确定") {
                    @Override
                    public void onPositive(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        view.setResult(Activity.RESULT_OK, null);
                        view.finish();
                    }
                });
            }

            @Override
            public void onFail(int code, String msg) {
                view.loaded();
                view.prompt(false, msg + ",是否继续打印", new OnPromptListener("确定", "取消") {
                    @Override
                    public void onPositive(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        print();
                    }

                    @Override
                    public void onNegative(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        view.setResult(Activity.RESULT_OK, null);
                        view.finish();
                    }
                });
            }
        });
    }
}
